package util

import (
	"github.com/stretchr/testify/assert"
	"gitverse.ru/synapse/kubelatte/pkg/observability/logs"
	"go.uber.org/zap"
	corev1 "k8s.io/api/core/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"testing"
)

func TestMatchLabels(t *testing.T) {
	logs.Logger = zap.NewNop()
	ns := corev1.Namespace{
		ObjectMeta: v1.ObjectMeta{
			Name:      "Test",
			Namespace: "Test",
			Labels: map[string]string{
				"test": "test",
			},
			Annotations: map[string]string{
				"test": "test",
			},
		},
	}
	selector := NamespaceSelector{
		LabelSelector: v1.LabelSelector{
			MatchLabels: nil,
			MatchExpressions: []v1.LabelSelectorRequirement{
				{
					Key:      "test",
					Operator: "In",
					Values: []string{
						"test",
					},
				},
			},
		},
		Include: nil,
		Exclude: nil,
	}
	got, err := MatchLabels(&ns, &selector.LabelSelector)
	assert.NoError(t, err)
	assert.True(t, got)
}

func TestMatchPattern(t *testing.T) {
	b1 := MatchPattern("*", "test")
	assert.True(t, b1)
	b2 := MatchPattern("", "test")
	assert.True(t, b2)
	b3 := MatchPattern("-", "test")
	assert.True(t, !b3)
	b4 := MatchPattern("-", "")
	assert.True(t, b4)
	b5 := MatchPattern("te*", "test")
	assert.True(t, b5)
	b6 := MatchPattern("asd,test", "test")
	assert.True(t, b6)
}

func TestNamespaceSelector_MatchNamespace(t *testing.T) {
	logs.Logger = zap.NewNop()
	ns := corev1.Namespace{
		ObjectMeta: v1.ObjectMeta{
			Name:      "Test",
			Namespace: "Test",
			Labels: map[string]string{
				"test": "test",
			},
			Annotations: map[string]string{
				"test": "test",
			},
		},
	}
	selector := NamespaceSelector{
		LabelSelector: v1.LabelSelector{
			MatchLabels: nil,
			MatchExpressions: []v1.LabelSelectorRequirement{
				{
					Key:      "test",
					Operator: "In",
					Values: []string{
						"test",
					},
				},
			},
		},
		Include: nil,
		Exclude: nil,
	}
	b1 := selector.MatchNamespace(&ns)
	assert.True(t, b1)
}

func TestNamespaceSelector_MatchNamespaceName(t *testing.T) {
	logs.Logger = zap.NewNop()
	ns := corev1.Namespace{
		ObjectMeta: v1.ObjectMeta{
			Name:      "Test",
			Namespace: "Test",
			Labels: map[string]string{
				"test": "test",
			},
			Annotations: map[string]string{
				"test": "test",
			},
		},
	}
	selector := NamespaceSelector{
		Include: []string{
			"Test",
		},
		Exclude: nil,
	}
	b1 := selector.MatchNamespaceName(ns.Name)
	assert.True(t, b1)
}
